﻿using Application.Users.Commands.CreateUser;
using Application.Users.Commands.UpdateUser;
using Application.Users.Models;
using Application.Users.Queries.GetUser;
using Application.Validators;
using FluentValidation;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Shared.Http.APIResult;
using WebApi.AntiCorruptions;

namespace WebApi.Controllers
{
    [ApiController]
    [Route("/api/v2/users/bulk")]
    public class UserBulkController
        (IMediator mediator, IValidator<GetUserFilter> getUserFilterValidator)
        : ControllerBase
    {
        [HttpPost]
        [Route("login")]
        public async Task<ActionResult<UserItem>> GetUserByPhonePaswdHash(UserLoginQuery request, CancellationToken ct = default)
        {
            var user = await mediator.Send(request, ct);
            if (user is not null)
            {
                return Ok(user);
            }

            return NotFound();
        }

        [HttpPost]
        [Route("search")]
        public async Task<ActionResult<ApiResult<ICollection<GetUserModel>>>> GetUsers(GetUserFilter request)
        {
            var result = await getUserFilterValidator.ValidateAsync(request);
            if (!result.IsValid)
            {
                List<ErrorData> errors = [];
                result.Errors.ForEach(x => errors.Add(new($"{x.PropertyName}:{x.ErrorMessage}")));
                return BadRequest(ApiResult.Fail(ApiStatusCode.BusinessError, Guid.NewGuid(), errors));
            }

            var users = await mediator.Send(request, default);
            return Ok(ApiResult.Success(users, Guid.NewGuid()));//todo
        }

        [HttpPost]
        [Route("create")]
        public async Task<ApiResult<List<Guid>>> CreateUsers(CreateUserCommand request)
        {
            var result = await mediator.Send(request);
            return result.ToApiResult(Guid.NewGuid());
        }

        [HttpPost]
        [Route("update")]
        public async Task<ApiResult<List<Guid>>> UpdateUsers(UpdateUserCommand request)
        {
            var result = await mediator.Send(request);
            return result.ToApiResult(Guid.NewGuid());
        }
    }
}
